#include "stdafx.h"
#include "NotifyWnd.h"
#include "MainDlg.h"
#include "Settings.h"

LRESULT CNotifyWnd::actExit( WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled )
{
	DestroyWindow();
	return 0;
}

void CNotifyWnd::customizeMenu()
{
	m_bNowOnline = false;
	bool bEnable = false;
	LPWSTR label = L"Bring online";

	if( NULL != m_defaultDrive )
	{
		sDiskInfo ds;
		HRESULT hr = vdsDiskInfo( m_defaultDrive, &ds );
		if( SUCCEEDED( hr ) )
		{
			switch( ds.state )
			{
			case eDiskState::Online:
				label = L"Take offline";
				bEnable = true;
				m_bNowOnline = true;
				break;
			case eDiskState::Offline:
				bEnable = true;
				break;
			}
		}
	}

	MENUITEMINFO mi;
	ZeroMemory( &mi, sizeof( mi ) );
	mi.cbSize = sizeof( mi );
	mi.fMask = MIIM_STRING | MIIM_STATE;
	mi.fState = ( bEnable ) ? MFS_DEFAULT : MFS_DISABLED;
	mi.dwTypeData = label;
	SetMenuItemInfo( m_submenu, ID_TRAY_ONLINE, FALSE, &mi );
}

LRESULT CNotifyWnd::actOnline( WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled )
{
	if( NULL == m_defaultDrive )
		return 0;

	HRESULT hr = S_OK;

	if( m_bNowOnline )
		hr = vdsOffline( m_defaultDrive );
	else
		hr = vdsOnline( m_defaultDrive );

	if( FAILED( hr ) )
	{
		MessageBox( ErrorMessageW( hr ) );
		return 0;
	}

	updateTooltip();

	return 0;
}

LRESULT CNotifyWnd::actConfigure( WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled )
{
	if( m_bConfiguring )
		return 0;
	m_bConfiguring = true;

	CMainDlg dlg;
	HRESULT hr = dlg.initialize( m_pService );
	if( FAILED( hr ) )
	{
		MessageBox( ErrorMessageW( hr ), L"", MB_OK | MB_ICONERROR );
	}
	else if( IDOK == dlg.DoModal( m_hWnd ) )
	{
		listDevices();
		updateTooltip();
	}

	m_bConfiguring = false;
	return 0;
}

HRESULT CNotifyWnd::listDevices()
{
	m_defaultDrive = NULL;
	m_strTooltip = L"";

	// List the drives
	HRESULT hr = vdsList( m_pService, m_drives );
	CHECK( hr, "vdsList failed" );

	// Read the setting
	CString defaultDrive;
	hr = settingRead( defaultDrive );
	if( FAILED( hr ) )
		return S_FALSE;

	sDiskInfo ds;
	for( size_t i = 0; i < m_drives.GetCount(); i++ )
	{
		hr = vdsDiskInfo( m_drives[ i ], &ds );
		if( FAILED( hr ) )
			continue;
		if( ds.displayName == defaultDrive )
		{
			m_defaultDrive = m_drives[ i ];
			m_strTooltip.Format( L"Managing %s %s.\nCurrently %s.",
				LPCTSTR( ds.getSizeString() ),
				LPCTSTR( defaultDrive ),
				LPCTSTR( ds.getStateString().MakeLower() ) );
			m_bNowOnline = ( ds.state == eDiskState::Online );
			break;
		}
	}

	return S_OK;
}